package helen.core.tools.download;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import helen.core.R;
import helen.core.tools.appmonitor.EventLog;
import helen.core.tools.utils.FileOpenUtils;

/**
 * 文件下载管理器
 * Created by cssnote on 2015/12/30.
 */
public class DownLoadManager {
    private static final int UPDARE_TOKEN = 0x23;
    private String fileUrl = "";
    private Context context;
    private String path;
    private String fileName;
    private ProgressBar progressBar;
    private boolean isCancel;
    private AlertDialog dialog;
    private int curProgress;

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDARE_TOKEN:
                    progressBar.setProgress(curProgress);
                    break;
            }
        }
    };

    public DownLoadManager(String url, Context context, String path, String fileName) {
        this.fileUrl = url;
        this.context = context;
        this.fileName = fileName;
        this.path = Environment.getExternalStorageDirectory() + File.separator + path + File.separator;
    }

    /**
     * 显示下载进度对话框
     */
    public void showDownloadDialog() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_progressbar, null);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("下载"+fileName);
        builder.setView(view);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                isCancel = true;
            }
        });
        dialog = builder.create();
        dialog.show();
        downloadApp();
    }

    /**
     * 下载新版本应用
     */
    private void downloadApp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                InputStream in = null;
                FileOutputStream out = null;
                HttpURLConnection conn = null;
                try {
                    url = new URL(fileUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; Android 4.4.2; MX4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Mobile Crosswalk/10.39.235.16 Mobile Safari/537.36");
                    conn.connect();
                    String requestMsg = conn.getResponseMessage();
                    String code = conn.getResponseCode()+"";
                    in = conn.getInputStream();
                    long fileLength = conn.getContentLength();
                    File filePath = new File(path);
                    if (!filePath.exists()) {
                        filePath.mkdir();
                    }
                    out = new FileOutputStream(new File(path+fileName));
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    long readedLength = 0l;
                    while ((len = in.read(buffer)) != -1) {
                        // 用户点击“取消”按钮，下载中断
                        if (isCancel) {
                            break;
                        }
                        out.write(buffer, 0, len);
                        readedLength += len;
                        curProgress = (int) (((float) readedLength / fileLength) * 100);
                        handler.sendEmptyMessage(UPDARE_TOKEN);
                        if (readedLength >= fileLength) {
                            dialog.dismiss();
                            // 下载完毕，打开文件
                            Intent intent = FileOpenUtils.openFile(path+fileName);
                            try{
                                context.startActivity(intent);
                            }catch (Exception e){
                                EventLog.GetInstance().PushEvent("DownLoadManager",e.getMessage());
                            }
                            break;
                        }
                    }
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                    dialog.dismiss();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

}
